<template>
  <div>
    <el-card shadow="never">
      <!-- 加载状态 -->
      <el-loading
        v-if="loading"
        text="数据加载中..."
        fullscreen
        background="rgba(255, 255, 255, 0.8)"
      />

      <!-- 欢迎信息 -->
      <!-- <div class="flex items-center">
        <el-avatar :src="avatar" :size="70" class="mr-16px">
          <img src="@/assets/imgs/avatar.gif" alt="默认头像" />
        </el-avatar>
        <div>
          <div class="text-20px">
            {{ t('workplace.welcome') }} {{ username }} {{ t('workplace.happyDay') }}
          </div>
          <div class="mt-10px text-14px text-gray-500">
            {{ t('workplace.toady') }}，20℃ - 32℃！
          </div>
        </div>
      </div> -->

      <!-- 图表区域：柱状图 + 饼状图 左右布局 -->
      <div class="mt-8 grid grid-cols-1 md:grid-cols-2 gap-8">
        <!-- 柱状图：原始数据展示 -->
        <div class="bg-white p-4 rounded-lg shadow-sm">
          <h3 class="text-lg font-medium mb-4">样本统计</h3>
          <EChart :options="barChartOptions" height="600px" />
        </div>

        <!-- 饼状图：原始数据占比 -->
        <div class="bg-white p-4 rounded-lg shadow-sm">
          <h3 class="text-lg font-medium mb-4">样本统计</h3>
          <EChart :options="pieChartOptions" height="600px" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { set } from 'lodash-es'
import type { EChartsOption } from 'echarts'
import { useUserStore } from '@/store/modules/user'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import EChart from '@/components/Echart/src/Echart.vue'
import { ElMessage } from 'element-plus'
import { JkProductApi, JkProductVO } from '@/api/jikong/jkProduct'

defineOptions({ name: 'WorkplaceIndex' })

// 国际化与路由
const { t } = useI18n()
const router = useRouter()
const userStore = useUserStore()

// 状态管理
const loading = ref(true)
const avatar = userStore.getUser.avatar || ''
const username = userStore.getUser.nickname || '未知用户'

// 1. 柱状图配置（原始数据展示）
const barChartOptions = reactive<EChartsOption>({
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'shadow' },
    formatter: '{b}: {c} 份'
  },
  legend: { show: false },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%', // 增加底部空间以适应更多标签
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      rotate: 45, // 旋转角度更大，避免文字重叠
      interval: 0,
      fontSize: 11,
      align: 'right'
    }
  },
  yAxis: {
    type: 'value',
    nameTextStyle: { fontSize: 12 },
    axisLabel: { formatter: '{value} 份' }
  },
  series: [
    {
      type: 'bar',
      data: [],
      barWidth: '50%',
      itemStyle: {
        color: (params) => {
          // 使用更多样的颜色方案
          const colorList = [
            '#409EFF',
            '#67C23A',
            '#E6A23C',
            '#F56C6C',
            '#909399',
            '#C06C84',
            '#38B2AC',
            '#FF9800',
            '#9C27B0',
            '#2196F3',
            '#00BCD4',
            '#8BC34A',
            '#FF5722'
          ]
          return colorList[params.dataIndex % colorList.length]
        }
      }
    }
  ]
})

// 2. 饼状图配置（原始数据占比）
const pieChartOptions = reactive<EChartsOption>({
  title: {
    left: 'center',
    textStyle: { fontSize: 14 },
    subtextStyle: { fontSize: 12, color: '#909399' }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {c} 份 ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: '5%',
    top: 'center',
    textStyle: { fontSize: 11 }
  },
  series: [
    {
      name: '样本统计',
      type: 'pie',
      radius: ['25%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 4,
        borderColor: '#fff',
        borderWidth: 1
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 14,
          fontWeight: 'bold'
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.3)'
        }
      },
      labelLine: { show: false },
      data: []
    }
  ]
})

// 存储原始数据
const rawData = []

/**
 * 请求样本统计数据并更新图表
 * 完全使用原始数据，不进行任何合并处理
 */
const getSampleStatistics = async () => {
  try {
    loading.value = true
    const response = await JkProductApi.getStatistics()
    // 存储原始数据
    rawData.value = response

    // 直接使用原始数据创建图表
    const sampleNames = response.map((item) => item.name.trim())
    const sampleValues = response.map((item) => item.value)

    // 更新柱状图数据
    barChartOptions.xAxis.data = sampleNames
    barChartOptions.series[0].data = sampleValues

    // 更新饼状图数据（直接使用原始数据）
    pieChartOptions.series[0].data = response.map((item) => ({
      name: item.name.trim(),
      value: item.value
    }))
  } catch (error) {
    console.error('样本统计数据加载失败：', error)
    ElMessage.error(t('workplace.dataLoadFail'))
  } finally {
    loading.value = false
  }
}

// 页面挂载时加载数据
onMounted(() => {
  getSampleStatistics()
})
</script>

<style scoped>
/* 布局相关样式 */
.grid {
  display: grid;
}
.grid-cols-1 {
  grid-template-columns: repeat(1, minmax(0, 1fr));
}
.md\:grid-cols-2 {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.gap-8 {
  gap: 2rem;
}
.mt-8 {
  margin-top: 2rem;
}

/* 卡片样式 */
.p-4 {
  padding: 1rem;
}
.rounded-lg {
  border-radius: 0.5rem;
}
.shadow-sm {
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

/* 文本样式 */
.text-lg {
  font-size: 1.125rem;
}
.font-medium {
  font-weight: 500;
}
.mb-4 {
  margin-bottom: 1rem;
}
.text-20px {
  font-size: 1.25rem;
}
.text-14px {
  font-size: 0.875rem;
}
.text-gray-500 {
  color: #6b7280;
}
.mr-16px {
  margin-right: 1rem;
}
.mt-10px {
  margin-top: 0.625rem;
}
</style>